package cn.shyouchi.wuguanjia.android.ui.attendance;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.joda.time.DateTime;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.shyouchi.wuguanjia.android.R;
import cn.shyouchi.wuguanjia.android.api.attendance.AttendanceApi;
import cn.shyouchi.wuguanjia.android.base.BaseActivity;
import cn.shyouchi.wuguanjia.android.components.storage.UserStorage;
import cn.shyouchi.wuguanjia.android.event.SignInEvent;
import cn.shyouchi.wuguanjia.android.event.SignOutEvent;
import cn.shyouchi.wuguanjia.android.event.SignStateEvent;
import cn.shyouchi.wuguanjia.android.ui.attendance.signin.SignInActivity;
import cn.shyouchi.wuguanjia.android.ui.attendance.signout.SignOutActivity;
import cn.shyouchi.wuguanjia.android.ui.attendance.statistics.StaffStatisticsActivity;
import cn.shyouchi.wuguanjia.android.ui.attendance.temporary.StaffTemporaryActivity;
import cn.shyouchi.wuguanjia.android.ui.attendance.temporary.TemporaryTaskEntity;
import cn.shyouchi.wuguanjia.android.ui.event.temporary.TemporaryEntity;
import cn.shyouchi.wuguanjia.android.utils.ToastUtil;
import cn.shyouchi.wuguanjia.android.widget.CheckDetailPop;
import cn.shyouchi.wuguanjia.android.widget.TopBar;
import noman.weekcalendar.WeekCalendar;
import noman.weekcalendar.listener.OnDateClickListener;
import noman.weekcalendar.listener.OnWeekChangeListener;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

import static cn.shyouchi.wuguanjia.android.R.id.topBar;

public class AttendanceActivity extends BaseActivity implements AttendanceContract.View {

    @BindView(topBar)
    TopBar mTopBar;
    @BindView(R.id.rv_attendance_module)
    RecyclerView mRvAttendanceModule;

    @BindView(R.id.weekCalendar)
    WeekCalendar mWeekCalendar;

    AttendanceModuleAdapter mModuleAdapter;
    List<AttendanceModuleEntity> mModuleEntities = new ArrayList<>();
    @BindView(R.id.tv_person_name)
    TextView mTvPersonName;
    AttendanceApi mAttendanceApi;
    private SimpleDateFormat dateFormator = new SimpleDateFormat("yyyy-MM");
    List<String> monthPool = new ArrayList<>();
    Map<String, AttendanceEntity.ResultMessageBean> mResultMessageBeanMap = new HashMap<>();

    RankDayDecorator mRankDayDecorator;

    TemporaryEntity.ResultMessageBean task;


    UserStorage mUserStorage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public int initContentView() {
        return R.layout.activity_attendance;
    }

    @Override
    public void initInjector() {
        mAttendanceApi = new AttendanceApi(mContext);
        mUserStorage = new UserStorage(mContext);

    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
        mTopBar.setTitle(getTitle().toString());
        mTopBar.setLeftIcon(R.mipmap.ic_back);
        setSupportActionBar(mTopBar.getToolbar());

        EventBus.getDefault().register(this);

        mModuleEntities.add(new AttendanceModuleEntity(SignInActivity.class, R.mipmap.ic_attendance_module_sign_in, "签到"));
        mModuleEntities.add(new AttendanceModuleEntity(SignOutActivity.class, R.mipmap.ic_attendance_module_sign_out, "签退"));
//        mModuleEntities.add(new AttendanceModuleEntity(StaffReportActivity.class, R.mipmap.ic_attendance_module_report, "报岗"));
//        mModuleEntities.add(new AttendanceModuleEntity(OutsideActivity.class, R.mipmap.ic_home_module_polling, "外出签到"));
        mModuleEntities.add(new AttendanceModuleEntity(StaffTemporaryActivity.class, R.mipmap.ic_attendance_module_temporary, "临保"));
//        mModuleEntities.add(new AttendanceModuleEntity(ExtraWorkActivity.class, R.mipmap.ic_attendance_module_extra_work, "加班考勤"));
        mModuleEntities.add(new AttendanceModuleEntity(StaffStatisticsActivity.class, R.mipmap.ic_attendance_module_statistics, "考勤记录"));

        mModuleAdapter = new AttendanceModuleAdapter(mModuleEntities, this);
        mTvPersonName.setText(String.format("%1s | %2s", mUserStorage.getUserData().getName(), mUserStorage.getUserData().getPermissions_name()));

        mWeekCalendar.setOnWeekChangeListener(new OnWeekChangeListener() {
            @Override
            public void onWeekChange(DateTime dateTime, boolean forward) {
                if (forward) {
                    if (monthPool.contains(dateFormator.format(dateTime.plusDays(7).getMillis()))) {
                        //do nothing
                    } else {
                        //do something
                        fetchMonthSignInfo(dateTime.plusDays(7).getMillis());
                    }
                } else {
                    if (monthPool.contains(dateFormator.format(dateTime.plusDays(-7).getMillis()))) {
                        //do nothing
                    } else {
                        //do something
                        fetchMonthSignInfo(dateTime.plusDays(-7).getMillis());
                    }
                }
            }
        });


        mRankDayDecorator = new RankDayDecorator(mContext, mResultMessageBeanMap);
        mWeekCalendar.setDayDecorator(mRankDayDecorator);
        mWeekCalendar.setOnDateClickListener(new OnDateClickListener() {
            @Override
            public void onDateClick(DateTime dateTime) {
                if (mRankDayDecorator.hasData(dateTime)) {
                    showRankDetail(mRankDayDecorator.getData(dateTime));
                } else {
                    ToastUtil.showToast(new SimpleDateFormat("yyyy-MM-dd").format(dateTime.getMillis()) + "无考勤信息");
                }
//
            }
        });

        mRvAttendanceModule.setLayoutManager(new GridLayoutManager(mContext, 2));
        mRvAttendanceModule.setAdapter(mModuleAdapter);
        fetchMonthSignInfo(System.currentTimeMillis());
        fetchTemporaryTask();


    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }


    private void showRankDetail(AttendanceEntity.ResultMessageBean bean) {

//        View v = LayoutInflater.from(mContext).inflate(R.layout.pop_attendance_rank_detail_layout, null);
//        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//        v.setLayoutParams(params);
//
//        PopupWindow popupWindow = new PopupWindow(v, v.getMeasuredWidth(), v.getMeasuredHeight());
//        popupWindow.setFocusable(true);
//        popupWindow.setOutsideTouchable(true);
//        popupWindow.setBackgroundDrawable(new BitmapDrawable());
//        popupWindow.showAsDropDown(mWeekCalendar);

        CheckDetailPop pop = new CheckDetailPop(this, bean);
        pop.showPopupWindow(mWeekCalendar);

    }

    @OnClick(R.id.tv_person_name)
    public void onClick() {


    }


    public void fetchMonthSignInfo(final long time) {
        mAttendanceApi.getUserSchedulingList(new SimpleDateFormat("yyyy-MM-dd").format(time))
                .subscribeOn(Schedulers.io())
                .map(new Func1<AttendanceEntity, List<AttendanceEntity.ResultMessageBean>>() {
                    @Override
                    public List<AttendanceEntity.ResultMessageBean> call(AttendanceEntity entity) {
                        return entity.getResultMessage();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<AttendanceEntity.ResultMessageBean>>() {
                    @Override
                    public void onCompleted() {
                        monthPool.add(dateFormator.format(time));

                        if (mRankDayDecorator.hasTodayData()) {
                            EventBus.getDefault().post(new SignInEvent(mRankDayDecorator.getTodayData().getCheckin() != null));
                        }
                        if (mRankDayDecorator.hasTodayData()) {
                            EventBus.getDefault().post(
                                    new SignOutEvent(mRankDayDecorator.getTodayData().getSignback() != null));
                        }

                        mWeekCalendar.updateUi();
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        ToastUtil.showToast("值班信息更新失败");
                    }

                    @Override
                    public void onNext(List<AttendanceEntity.ResultMessageBean> resultMessageBeen) {
                        for (AttendanceEntity.ResultMessageBean b : resultMessageBeen) {
                            mResultMessageBeanMap.put(b.getDay(), b);
                        }
                    }
                });
    }

    public void fetchTemporaryTask() {
        mAttendanceApi.getTemporaryTask()
                .subscribeOn(Schedulers.io())
                .flatMap(new Func1<TemporaryTaskEntity, Observable<TemporaryEntity.ResultMessageBean>>() {
                    @Override
                    public Observable<TemporaryEntity.ResultMessageBean> call(TemporaryTaskEntity entity) {
                        return Observable.from(entity.getResultMessage());
                    }

                })
                .first()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<TemporaryEntity.ResultMessageBean>() {
                    @Override
                    public void onCompleted() {
                        mModuleAdapter.notifyItemChanged(3);
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(TemporaryEntity.ResultMessageBean bean) {
                        task = bean;
                        mModuleEntities.get(2).setName(String.format("临保-%1s-%2s",
                                bean.getStartingtime().substring(0, 10), bean.getAddress()));
                    }
                });

    }


    @Override
    public void onModuleClick(AttendanceModuleEntity entity) {

        if (entity.getTarget() == SignInActivity.class) {
            if (mRankDayDecorator.hasTodayData()) {
                Intent intent = new Intent(mContext, entity.getTarget());
                intent.putExtra("attendance", mRankDayDecorator.getTodayData());
                startActivity(intent);
            } else {
                ToastUtil.showToast(new SimpleDateFormat("yyyy-MM-dd").format(DateTime.now().getMillis()) + "不需要考勤");
            }
        } else if (entity.getTarget() == SignOutActivity.class) {
//            if (mRankDayDecorator.hasTodayData()) {
            Intent intent = new Intent(mContext, entity.getTarget());
//                intent.putExtra("attendance", mRankDayDecorator.getTodayData());
            startActivity(intent);
//            } else {
//                ToastUtil.showToast(new SimpleDateFormat("yyyy-MM-dd").format(DateTime.now().getMillis()) + "不需要考勤");
//            }

        } else if (entity.getTarget() == StaffTemporaryActivity.class) {
            if (task != null) {
                Intent intent = new Intent(mContext, entity.getTarget());
                intent.putExtra("task", task);
                startActivity(intent);
            } else {
                ToastUtil.showToast("没有临保任务");
            }

        } else {
            startActivity(new Intent(mContext, entity.getTarget()));
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSignStateChange(SignStateEvent event) {
        fetchMonthSignInfo(System.currentTimeMillis());
    }

    @Override
    protected void onDestroy() {
        mUserStorage.detach();
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
